<template>
  <el-dialog 
    v-model="dialogVisible" 
    title="服务人员详情" 
    width="900px" 
    :close-on-click-modal="false" 
    destroy-on-close 
    class="staff-detail-dialog"
  >
    <el-descriptions v-loading="loading" :column="2" border class="staff-detail">
      <el-descriptions-item label="联系电话" :label-width="100">
        {{ staff.user?.phone }}
      </el-descriptions-item>
      <el-descriptions-item label="工作经验" :label-width="100">
        {{ staff.experience }}年
      </el-descriptions-item>
      <el-descriptions-item label="服务价格" :label-width="100">
        ¥{{ staff.pricePerHour }}/小时
      </el-descriptions-item>
      <el-descriptions-item label="完成订单" :label-width="100">
        {{ staff.totalOrders }}单
      </el-descriptions-item>
      <el-descriptions-item label="完成率" :label-width="100">
        {{ staff.completionRate }}%
      </el-descriptions-item>
      <el-descriptions-item label="服务区域" :label-width="100">
        {{ staff.workArea }}
      </el-descriptions-item>
      <el-descriptions-item label="服务类型" :span="2" :label-width="100">
        <el-tag v-for="type in staff.serviceType" :key="type" class="detail-tag" effect="plain">
          {{ type }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="个人简介" :span="2" :label-width="100">
        {{ staff.description || '暂无简介' }}
      </el-descriptions-item>
      <el-descriptions-item label="证书信息" :span="2" :label-width="100">
        <el-table
          v-if="staff.certificates && staff.certificates.length"
          :data="staff.certificates"
          size="small"
          border
          style="width: 100%;"
        >
          <el-table-column prop="name" label="证书名称" min-width="120" />
          <el-table-column prop="code" label="证书编号" min-width="120" />
          <el-table-column prop="issueDate" label="发证日期" min-width="120" />
        </el-table>
        <span v-else>暂无证书信息</span>
      </el-descriptions-item>
    </el-descriptions>

    <!-- 服务项目列表 -->
    <div class="service-selection" v-if="showServiceSelection">
      <div class="section-title">
        <span class="title-text">可预约服务</span>
        <el-tag type="success" effect="plain" class="service-count" v-if="staffServices.length">
          {{ staffServices.length }} 个服务项目
        </el-tag>
      </div>

      <div class="service-list">
        <template v-if="staffServices.length">
          <div 
            v-for="service in staffServices" 
            :key="service.id"
            class="service-item"
            :class="{ 'is-selected': selectedServiceId === service.id }"
            @click="selectService(service)"
          >
            <div class="service-info">
              <div class="service-header">
                <span class="service-title">{{ service.title }}</span>
                <el-tag 
                  size="small" 
                  :type="service.status === 1 ? 'success' : 'info'"
                  effect="plain"
                >
                  {{ service.status === 1 ? '可预约' : '暂停预约' }}
                </el-tag>
              </div>
              <div class="service-category" v-if="service.category">
                <el-tag size="small" type="warning" effect="plain">
                  {{ service.category.categoryName }}
                </el-tag>
              </div>
              <div class="service-desc" v-if="service.description">
                {{ service.description }}
              </div>
            </div>
            <div class="service-price-box">
              <span class="price-label">服务价格</span>
              <span class="price-value">¥{{ service.price }}</span>
              <span class="price-unit">/小时</span>
            </div>
          </div>
        </template>
        <el-empty v-else description="暂无可预约服务" />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button 
          type="primary" 
          @click="handleOrder" 
          :disabled="!selectedServiceId"
        >
          立即预约
        </el-button>
        <el-button type="primary" @click="showChat">
          在线咨询
        </el-button>
      </div>
    </template>

    <chat-window 
      v-model="chatVisible"
      :target-id="staff.id"
      :show-session-list="false"
    />
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import ChatWindow from '@/components/common/ChatWindow.vue'

// 保存 props 的返回值
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  staffId: {
    type: [String, Number],
    default: null
  }
})

// 保存 emits 的返回值
const emit = defineEmits({
  'update:modelValue': (value) => typeof value === 'boolean',
  'close': () => true
})

const router = useRouter()
const userStore = useUserStore()
const dialogVisible = ref(false)
const loading = ref(false)
const staff = ref({})
const staffServices = ref([])
const selectedServiceId = ref(null)
const showServiceSelection = ref(true)
const chatVisible = ref(false)

// 获取服务人员详情
const fetchStaffDetail = async () => {
  loading.value = true
  try {
    const [staffRes, servicesRes] = await Promise.all([
      request.get(`/staff/${props.staffId}`),
      request.get(`/staff/service-items/list?staffId=${props.staffId}`, null, {
        showDefaultMsg: false
      })
    ])
    
    // 验证并设置 staff 数据
    if (staffRes) {
      staff.value = staffRes
    } else {
      console.error('获取服务人员信息失败：返回数据为空')
      ElMessage.error('获取服务人员信息失败')
      return
    }

    // 验证并设置服务项目数据
    if (servicesRes === null || servicesRes === undefined) {
      // 如果返回值为 null 或 undefined，设置为空数组
      staffServices.value = []
    } else if (Array.isArray(servicesRes)) {
      // 如果是数组，处理数据
      staffServices.value = servicesRes.map(item => ({
        id: item.serviceId,
        title: item.serviceItem?.title || '未知服务',
        price: item.serviceItem?.price || 0,
        status: item.serviceItem?.status || 0,
        category: item.serviceItem?.category || null,
        description: item.serviceItem?.description || ''
      }))
    } else {
      // 如果既不是 null/undefined 也不是数组，设置为空数组
      console.warn('服务项目列表数据格式不正确，设置为空数组')
      staffServices.value = []
    }
  } catch (error) {
    console.error('获取服务人员详情失败:', error)
    ElMessage.error('获取服务人员详情失败')
    staffServices.value = []
  } finally {
    loading.value = false
  }
}

// 重置数据
const resetData = () => {
  staff.value = {}
  staffServices.value = []
  selectedServiceId.value = null
}

// 监听 modelValue 变化
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val && props.staffId) {
    fetchStaffDetail()
  }
}, { immediate: true })

// 监听对话框关闭
watch(dialogVisible, (val) => {
  if (val !== props.modelValue) {
    emit('update:modelValue', val)
  }
  if (!val) {
    emit('close')
    resetData()
  }
})

// 选择服务
const selectService = (service) => {
  selectedServiceId.value = service.id === selectedServiceId.value ? null : service.id
}

// 处理预约
const handleOrder = () => {
  if (!selectedServiceId.value) {
    ElMessage.warning('请选择服务项目')
    return
  }

  // 检查是否登录
  if (!userStore.isLoggedIn) {
    ElMessageBox.confirm('请先登录后再进行预约', '提示', {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push('/login')
    }).catch(() => {
      // 用户点击取消按钮时，不做任何操作
    })
    return
  }

  // 跳转到预约页面
  router.push({
    path: '/order/create',
    query: {
      staffId: staff.value.id,
      serviceId: selectedServiceId.value
    }
  })
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}

const showChat = () => {
  // 检查是否登录
  if (!userStore.isLoggedIn) {
    ElMessageBox.confirm('请先登录后再进行咨询', '提示', {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push('/login')
    }).catch(() => {
      // 用户点击取消按钮时，不做任何操作
    })
    return
  }
  chatVisible.value = true
}
</script>

<style lang="scss" scoped>
.staff-detail-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }

  .staff-detail {
    :deep(.el-descriptions__label) {
      width: 100px;
      justify-content: flex-end;
      padding-right: 12px;
    }

    :deep(.el-descriptions__content) {
      padding: 12px 15px;
    }

    .detail-tag {
      margin-right: 8px;
      margin-bottom: 4px;
    }
  }

  .service-selection {
    margin-top: 24px;
    border-top: 1px solid var(--el-border-color-light);
    padding-top: 24px;

    .section-title {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 20px;

      .title-text {
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }

      .service-count {
        font-size: 13px;
      }
    }

    .service-list {
      display: flex;
      flex-direction: column;
      gap: 12px;
      max-height: 400px;
      overflow-y: auto;
      padding: 4px;

      .service-item {
        display: flex;
        justify-content: space-between;
        align-items: stretch;
        padding: 16px 20px;
        border: 2px solid var(--el-border-color-light);
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        background-color: var(--el-bg-color);
        
        &:hover {
          border-color: var(--el-color-primary-light-5);
          background-color: var(--el-color-primary-light-9);
          transform: translateX(4px);
        }
        
        &.is-selected {
          background-color: var(--el-color-primary);
          border-color: var(--el-color-primary);
          transform: translateX(4px);
          box-shadow: 0 4px 16px rgba(var(--el-color-primary-rgb), 0.2);
          
          .service-info {
            .service-title,
            .service-desc {
              color: #ffffff;
            }
          }

          .service-price-box {
            background-color: rgba(255, 255, 255, 0.1);
            
            .price-label,
            .price-value,
            .price-unit {
              color: #ffffff;
            }
          }
        }

        .service-info {
          flex: 1;
          margin-right: 20px;
          display: flex;
          flex-direction: column;
          gap: 8px;

          .service-header {
            display: flex;
            align-items: center;
            gap: 12px;

            .service-title {
              font-size: 16px;
              font-weight: 500;
              color: var(--el-text-color-primary);
            }
          }

          .service-category {
            display: flex;
            gap: 8px;
          }

          .service-desc {
            font-size: 13px;
            color: var(--el-text-color-secondary);
            line-height: 1.5;
            margin-top: 4px;
          }
        }

        .service-price-box {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 12px 20px;
          background-color: var(--el-color-primary-light-9);
          border-radius: 6px;
          min-width: 120px;

          .price-label {
            font-size: 12px;
            color: var(--el-text-color-secondary);
            margin-bottom: 4px;
          }

          .price-value {
            font-size: 20px;
            font-weight: 600;
            color: var(--el-color-danger);
            line-height: 1.2;
          }

          .price-unit {
            font-size: 12px;
            color: var(--el-text-color-secondary);
            margin-top: 2px;
          }
        }
      }
    }
  }
}

.logo-section {
  display: flex;
  align-items: center;
  height: 64px;
  background: transparent; /* 确保无背景色 */
  box-shadow: none;        /* 确保无阴影 */
  margin: 0;
  padding: 0;
}

.logo-icon {
  height: 100%;
  width: auto;
  display: flex;
  align-items: center;
  background: transparent;
  margin: 0;
  padding: 0;
}

.logo-img {
  height: 100%;   /* 让图片高度与容器一致 */
  width: auto;
  background: transparent;
  margin: 0;
  padding: 0;
  box-shadow: none;
  border: none;
}

.service-item.is-selected .service-title {
  color: #fff !important;
}
.service-item.is-selected .el-tag {
  background-color: rgba(255,255,255,0.15) !important;
  color: #fff !important;
  border-color: #fff !important;
}

.service-item.is-selected .price-value {
  color: var(--el-color-danger) !important;
}
</style> 